package com.zp.qualitypractice.Mvp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;

import com.zp.qualitypractice.App;

import java.lang.ref.WeakReference;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by izp on 2017/5/28.
 */
public abstract class BaseBCActivity extends BaseActivity {
//public abstract class BaseBCActivity<T extends MvpBase.BasePresenter<MvpBase.BaseView>> extends BaseActivity {
//    要做成抽象的bindPresenter();这个方法需要具体实现

//    这个泛型该怎么解决？
    private Unbinder unbinder;
    protected MainBroadcaster mainBroadcaster;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setContentViewId());
        unbinder = ButterKnife.bind(this);
        mainBroadcaster = new MainBroadcaster(this);
        App.getApp().getBroadcast().registerReceiver(mainBroadcaster,setIntentFilter());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.getApp().getBroadcast().unregisterReceiver(mainBroadcaster);//ME：注册的尽量晚，取消注册得尽量早，以免收到广播是界面已经有问题了，当然，界面动作一定要tryCatch
        if (null!=unbinder){
            unbinder.unbind();
        }
    }

    protected abstract @LayoutRes int setContentViewId();
    public abstract void onBroadcastReceiver(Intent intent);
    public abstract IntentFilter setIntentFilter();

    static class MainBroadcaster extends BroadcastReceiver {
        static WeakReference sWeakActivity ;
        public MainBroadcaster(BaseBCActivity activity) {
            if (null ==sWeakActivity){
                sWeakActivity = new WeakReference<>(activity);
            }
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (null!=sWeakActivity && null!=sWeakActivity.get()){
                ((BaseBCActivity)sWeakActivity.get()).onBroadcastReceiver(intent);
            }
        }
    }
}
